package icu.wdtt.mapper;

import icu.wdtt.model.Authority;
import icu.wdtt.model.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface RoleMapper {


    @Select("SELECT * FROM role")
    @Results(
            {
                    @Result(column = "rid" , property = "rid"),
                    @Result(column = "rname" , property = "rdescribe"),
                    @Result(
                            property = "authorityList",
                            column = "rid" ,
                            javaType = List.class,
                            many = @Many(select = "icu.wdtt.mapper.RoleMapper.getRoleAndAuthority")
                    ),
            }
    )
    public List<Role> getAll();

    @Select("SELECT * FROM role WHERE rid=#{rid}")
    @Results(
            {
                    @Result(column = "rid" , property = "rid"),
                    @Result(column = "rname" , property = "rdescribe"),
                    @Result(
                            property = "authorityList",
                            column = "rid" ,
                            javaType = List.class,
                            many = @Many(select = "icu.wdtt.mapper.RoleMapper.getRoleAndAuthority")
                    ),
            }
    )
    public Role get(int rid);

    @Insert("INSERT INTO role VALUES(null,#{rname},#{rdescribe})")
    @Options(useGeneratedKeys = true,keyProperty = "uid",keyColumn = "uid")
    public void add(Role role);

    @Delete("DELETE FROM role WHERE rid=#{rid}")
    public void del(int rid);


    @Update("UPDATE role SET rname=#{rname} , rdescribe=#{rdescribe} WHERE rid=#{rid}")
    public void update(Role role);

    @Select("SELECT  a.* FROM (SELECT * FROM role_authority WHERE rid=#{rid}) ra , authority a WHERE a.aid = ra.aid")
    public List<Authority> getRoleAndAuthority(int rid);

    @Select("SELECT * FROM role WHERE rname LIKE '%${rname}%' ")
    public List<Role> getName(@Param("rname") String rname);

    @Insert("INSERT INTO role_authority SET rid=#{rid},aid=#{aid}")
    public void addRoleAndAuthority(@Param("rid") int rid , @Param("aid") int aid);

    @Delete("DELETE FROM role_authority WHERE rid=#{rid}")
    public void delRoleAndAuthority(int rid);

    @Delete("DELETE FROm user_role WHERE rid=#{rid}")
    public void delRoleAndUser(int rid);

}
